package com.atguigu.network;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Demo05TCPServerAlways {

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(8888);

        // ★把处理客户端请求的操作放入一个永久循环中
        while (true) {
            System.out.println("服务器端就绪，等待客户端连接：");
            Socket socket = serverSocket.accept();

            // ★把处理请求的操作放入子线程中执行
            Runnable runnable = new Runnable() {
                @Override
                public void run() {
                    try {
                        InputStream inputStream = socket.getInputStream();
                        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                        StringBuffer stringBuffer = new StringBuffer();
                        String line = null;
                        while ((line = bufferedReader.readLine()) != null) {
                            stringBuffer.append(line);
                        }
                        System.out.println("服务器端接收到了客户端数据：" + stringBuffer.toString());

                        OutputStream outputStream = socket.getOutputStream();
                        PrintStream printStream = new PrintStream(outputStream);
                        printStream.print("☆服务器端返回的响应数据~~~");

                        socket.close();
                        System.out.println("服务器端处理本次请求完成，连接关闭");
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                }
            };

            new Thread(runnable).start();
        }

        // 不可达代码
        // serverSocket.close();
    }

}
